const send_msg = require("../dist/send-msg").send_msg();
const uuid = require('uuid');

async function get_id({ spaceid = null, file_name = null }) {
	try {
		const query = [{ "query_mode": 1, "spaceid": spaceid, "systemid": "11", "tablename": "base_js", "criteria": { "productid": { '$in': [spaceid, 'feidao_public'] }, "file_name": file_name }, "fields": { "_id": 1 }, "page_no": 1, "page_size": 1 }];
		const result = await send_msg("dbacc.find.intranet", query);
		return result[0]["dataArray"][0]['_id'];
	} catch (ex) {
		console.error("获取js文件失败.spaceId=" + spaceid + ", modelid=" + file_name, __filename);
		return null;
	}
}

/**
 * 常量说明 opflag
 *  1   （原数据）
 *  2   （删除）
 *  4   (新增)
 *  8   (修改)
 */

function get_save_data(_id, code, spaceid, productid, systemid, file_name) {
	if (_id) {
		// update
		return {
			"argjson": [{
				"opflag": 8,
				"tname": "base_js",
				"rowdata": {
					"file_cont": code,
					productid,
					file_name,
				},
				"criteria": {
					_id
				}
			}],
			spaceid,
			systemid
		};
	} else {
		_id = uuid();
		// add
		return {
			"argjson": [{
				"opflag": 4,
				"tname": "base_js",
				"rowdata": {
					"file_cont": code,
					productid,
					file_name,
					_id
				}
			}],
			spaceid,
			"systemid": "11"
		};
	}

}

async function save(code, spaceid, productid, file_name) {
	const id = await get_id({ spaceid, file_name });
	if (productid === 'feidao_public') {
		const curd1 = get_save_data(id, code, 'bjfeidao_353', productid, '1085', file_name);
		const result1 = await send_msg("dbacc.save.intranet", curd1);
		console.log("保存至业务库*********", result1)
		const curd2 = get_save_data(id, code, 'bjfeidao_353', productid, '11', file_name);
		const result2 = await send_msg("dbacc.save.intranet", curd2);
		console.log("保存至生产库*********", result2)
	} else {
		const curd = get_save_data(id, code, spaceid, productid, '11', file_name);
		const result = await send_msg("dbacc.save.intranet", curd);
		console.log("保存至业务库*********", result)
	}
}

module.exports = (code, spaceid, productid, file_name) => {
	save(code, spaceid, productid, file_name).then(() => {
		console.log('success.');
		process.exit();
	}, (err) => {
		console.log('fail.');
		console.error(err);
		process.exit();
	})
};

if (require.main === module) {
	async function main() {
		const file_names = ['zfb-payfinish'];
		await Promise.all(file_names.map(async (file_name) => {
			const m = require(`./${file_name}`);
			const code = m.code;
			const spaceid = m.spaceid;
			const productid = m.productid || spaceid;
			return await save(code, spaceid, productid, file_name);
		}));
		process.exit();
	}

	main();
}
